import Vue from 'vue'
import Vuex from 'vuex'
import {getItem, setItem} from "@/plugins";
import {LoginApi} from "@/api/apiFox";
import {Toast} from "vant";
import {encrypt} from "@/utils/AES";
const tokenKey = 'access_key'
const user = 'user'
const userInfo = 'userInfo'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: getItem(tokenKey),
    lang:getItem('lang') || {langText: navigator.language,value:navigator.languages[0]},
    User:getItem(userInfo) || ''
  },
  getters: {
  },
  mutations: {
    // 更新token
    saveToken(state, data) {
      state.token = data.userInfo.token
      state.User = encrypt(JSON.stringify(data.userInfo))
      setItem(userInfo,encrypt(JSON.stringify(data.userInfo)))
      setItem(tokenKey, state.token)
    },

    updateLang(state,data){
      state.lang=data
    }

  },
  actions: {
    loginSetToken({commit}, data) {
      return new Promise((resolve, reject) => {
        LoginApi(data).then(res => {
          commit('saveToken', res)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    updateLang({commit},data){
      commit('updateLang',data)
    }
    // 调用例子
    // this.$store.dispatch('loginSetToken',this.submitForm).then(res=>{
    //   this.interfaceLoading=false
    //   this.$router.replace('/home/chat')
    // }).catch(err=>{
    //   this.interfaceLoading=false
    //   this.verificationCode()
    // })
  },
  modules: {
  }
})
